using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;


	public partial class EditFile_ : System.Web.UI.Page
	{

		private void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				string filePath = Request.Params["File"];
				if (filePath != null)
				{
					if (Request.Params["CreateFile"] == null || Request.Params["CreateFile"]=="false")
					{
						// load the content of the specified text file in the textbox
						try
						{
							StreamReader sr = new StreamReader (File.Open(Server.MapPath(filePath), FileMode.Open) );
							FileContent.Text = sr.ReadToEnd();
							sr.Close();
						}
						catch (Exception exc)
						{
							StatusMessage.Text = exc.Message;
							StatusMessage.Visible = true;
						}
					}
					// set the Save As textbox with the path specified in the QueryString
					SaveAsPath.Text = filePath;
				}
			}
		}
		
		protected void Back_Click(object sender, EventArgs e)
		{
			// redirect to the referrer URL or to the BrowseFile.aspx page
			// if the referrer is null
			string filePath = Request.Params["File"];
			if (filePath != null && filePath != "/")
			{
				int lastSlashIndex = filePath.LastIndexOf("/");
				string folderPath = filePath.Substring(0, lastSlashIndex+1);
				Response.Redirect("BrowseFiles.aspx?Folder=" + folderPath);
			}
			else
				Response.Redirect("BrowseFiles.aspx");
		}

		protected void Save_Click(object sender, EventArgs e)
		{
			// save the text to the specified file
			// (the file is created ex-novo even if it already exists)
			try
			{
				string filePath = SaveAsPath.Text;
				if (!filePath.StartsWith("/")) filePath = "/" + filePath;
				StreamWriter sw = File.CreateText(Server.MapPath(filePath));
				sw.Write(FileContent.Text);
				sw.Close();
				StatusMessage.Text = "File successfully saved";
			}
			catch (Exception exc)
			{
				StatusMessage.Text = exc.Message;;
			}
			StatusMessage.Visible = true;
		}


		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion
	}
